<?php

	class DB 
	{
		
		const USERS_DB = 'users/.users.json';
		
		public static function get($key)
		{

			$entry = DB::_readData($key);
			return !empty($entry) ? (array)$entry : false;
		
		}
		
		public static function set($key, $value)
		{

			if ( is_array($value) )
			{
				$data = DB::_readData($key);
				$data[$key][] = $value;
				return DB::_writeData($data);
			}
			return FALSE;
		}
		
		public static function setUserAccount($value)
		{
			$value['password'] = sha1($value['password']);
			Session::set('feedback', array('type'=>'success', 
																				'message'=>'Account created', 
																				'description' => 'Your account has been created successfully!<br/>You may now use your credentials to log in.'));
			return DB::set('users', $value);
		}
		
		public static function getUserAccount($value)
		{
			if ( empty($value) )
			{
				return FALSE;
			}
			
			$entries = DB::get('users', $value);
			if ( !empty($entries) )
			{
				foreach($entries as $entry)
				{
					$entry = (array)$entry;
					if ( $value['phone'] === $entry['phone'] 
							&& sha1($value['password']) === $entry['password'] )
					{
						return $entry;
					}
				}
			}
			return FALSE;
			
		}
		
		private static function _writeData($data)
		{
			if (is_array($data))
			{
			
				$data = json_encode($data);
				$data = base64_encode($data);
				return file_put_contents(DB::USERS_DB, $data);
			}
			
			return FALSE;
		}
		
		private static function _readData($filter='')
		{
			$content = file_get_contents(DB::USERS_DB);
			$content = base64_decode($content);
			$content = (array)json_decode($content);
			
			return empty($content[ $filter ]) ? array() : $content[ $filter ];
			
		}

	}

?>
